package com.nfu.zlsp.dev.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.nfu.zlsp.dev.common.utils.PageUtils;
import com.nfu.zlsp.dev.common.utils.Query;
import com.nfu.zlsp.dev.dao.AddressDao;
import com.nfu.zlsp.dev.dao.TransportDao;
import com.nfu.zlsp.dev.dao.UserDao;
import com.nfu.zlsp.dev.entity.AddressEntity;
import com.nfu.zlsp.dev.entity.ConsignEntity;
import com.nfu.zlsp.dev.entity.TransportEntity;
import com.nfu.zlsp.dev.entity.UserEntity;
import com.nfu.zlsp.dev.entity.vo.QueryTransportVo;
import com.nfu.zlsp.dev.service.AddressService;
import com.nfu.zlsp.dev.service.TransportService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service("transportService")
public class TransportServiceImpl extends ServiceImpl<TransportDao, TransportEntity> implements TransportService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private AddressService addressService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TransportEntity> page = this.page(
                new Query<TransportEntity>().getPage(params),
                new QueryWrapper<TransportEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryTransportPageByInfo(Map<String, Object> params) {


        /**
         * 大致相当于
         * select xxx from transport t
         *            join user u
         *            join address a
         *            on t.t_user = u.id
         *            and t.pick_address = a.address_areaId.......
         *            ................
         */

        QueryWrapper<TransportEntity> queryWrapper = new QueryWrapper<>();
        String logisticsType = (String) params.get("logisticsType");
        String transportMode = (String) params.get("transportMode");
        String minPrice = (String) params.get("minPrice");
        String maxPrice = (String) params.get("maxPrice");
        String volume = (String) params.get("volume");
        String weight = (String) params.get("weight");
        String pickupTime = (String) params.get("pickupTime");
        String pickUpCity = (String) params.get("pickUpCity");
        String unloadCity = (String) params.get("unloadCity");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        queryWrapper.orderByDesc("creation_time");

        if(minPrice == null){
            queryWrapper.eq("state","0");
        }else{
            queryWrapper.eq("logistics_type",logisticsType).eq("transport_mode",transportMode).eq("state","0");
            queryWrapper.between("price",minPrice,maxPrice);
            queryWrapper.gt("pickup_Time",pickupTime);
            if (volume != "" ) {
                queryWrapper.eq("volume",volume);
            }
            if (weight != ""){
                queryWrapper.eq("weight",weight);
            }
        }



        IPage<TransportEntity> page = this.page(
                new Query<TransportEntity>().getPage(params),
                queryWrapper
        );

        List<TransportEntity> transportEntityList = page.getRecords();

        long t1 = 0;
        long t2 = 0;


        /**
         * 将搜集到的transport表信息结合其他数据封装成QueryTransportVo传给前端
         */
        List<QueryTransportVo> queryTransportVoList = transportEntityList.stream().map(transportEntity -> {
            QueryTransportVo queryTransportVo = new QueryTransportVo();
            BeanUtils.copyProperties(transportEntity, queryTransportVo);
            UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("id", transportEntity.getTUser()));

            //写入公司 ......
            queryTransportVo.setCompany(userEntity.getCompany());
            queryTransportVo.setEmail(userEntity.getEmail());
            queryTransportVo.setNumber(userEntity.getNumber());
            queryTransportVo.setUsername(userEntity.getUsername());

            //写入时效
            try {
                //long time1 = sdf.parse(sdf.format(transportEntity.getDeliveryTime())).getTime();
                //long time2 = sdf.parse(sdf.format(transportEntity.getPickupTime())).getTime();

                Long time1 = sdf.parse(transportEntity.getDeliveryTime()).getTime();
                Long time2= sdf.parse(transportEntity.getPickupTime()).getTime();
                queryTransportVo.setLimitTime((time1 - time2)/(1000 * 60 * 60));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //写出发地和目的地
            queryTransportVo.setBeginAddress(addressService.getAddressByRegionId(transportEntity.getPickupAddress()) + transportEntity.getPickupDetailAddress());
            queryTransportVo.setEndAddress(addressService.getAddressByRegionId(transportEntity.getUnloadAddress()) + transportEntity.getUnloadDetailAddress());

            /**
             * 删选出地址不符合查询条件的
             *  返回空的QueryTransportVo
             */
            if(minPrice != null){
                AddressEntity beginCity = addressDao.selectOne(new QueryWrapper<AddressEntity>().eq("address_areaId", transportEntity.getPickupAddress()));
                AddressEntity endCity = addressDao.selectOne(new QueryWrapper<AddressEntity>().eq("address_areaId", transportEntity.getUnloadAddress()));
                if(!(beginCity.getAddressRegionid().equals(pickUpCity) && endCity.getAddressRegionid().equals(unloadCity))){
                    //地址条件不符
                    return new QueryTransportVo();
                }
            }

            return queryTransportVo;

        }).collect(Collectors.toList());


        //用迭代器删除值为空的元素（迭代器遍历不会报错 foreach会）
        Iterator iterator = queryTransportVoList.iterator();
        while (iterator.hasNext()){
            QueryTransportVo vo = (QueryTransportVo) iterator.next();
            if(vo.getId() == null){
                iterator.remove();
            }

        }

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(queryTransportVoList);
        return pageUtils;

    }

    @Override
    public PageUtils queryMyTransportPage(UserEntity user) {

        QueryWrapper<TransportEntity> queryWrapper = new QueryWrapper<>();
        Map<String,Object> map = new HashMap<>();
        map.put("state","0");
        //查询 ”我的“  "未接单"
        queryWrapper.eq("state","0").eq("t_user",user.getId());
        IPage<TransportEntity> page = this.page(
                new Query<TransportEntity>().getPage(map),
                queryWrapper
        );

        List<TransportEntity> transportEntityList = page.getRecords();

        //根据地区编号查赋予细地址
        List<TransportEntity> collect = transportEntityList.stream().map(consignEntity -> {
            String pickAddress = addressService.getAddressByRegionId(consignEntity.getPickupAddress());
            String unloadAddress = addressService.getAddressByRegionId(consignEntity.getUnloadAddress());
            pickAddress += consignEntity.getPickupDetailAddress();
            unloadAddress += consignEntity.getUnloadDetailAddress();
            consignEntity.setPickupDetailAddress(pickAddress);
            consignEntity.setUnloadDetailAddress(unloadAddress);
            return consignEntity;
        }).collect(Collectors.toList());


        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(transportEntityList);
        return  pageUtils;
    }

    @Override
    public void cancelConsignById(String id) {
        this.baseMapper.deleteById(id);
    }


}







